package com.ecar.api.service.driver.impl;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ecar.api.async.AsyncTheadPool;
import com.ecar.api.rest.AbstractResource;
import com.ecar.api.service.common.ModelSetService;
import com.ecar.api.service.common.NotifyService;
import com.ecar.api.service.driver.DriverService;
import com.ecar.api.service.order.OrderService;
import com.ecar.api.service.temp.TempService;
import com.ecar.api.support.dto.DriverDto;
import com.ecar.api.support.util.DateUtil;
import com.ecar.api.support.util.PasswordUtil;
import com.ecar.api.support.util.Props;
import com.ecar.api.support.util.Redis;
import com.ecar.api.support.util.UuidUtils;
import com.ecar.cache.BeanSerializer;
import com.ecar.common.cipher.DES;
import com.ecar.common.dto.DataBean;
import com.ecar.common.util.BeanUtils;
import com.ecar.common.util.StringUtil;
import com.ecar.core.driver.dao.DriverMapper;
import com.ecar.core.driver.dao.ModelSetMapper;
import com.ecar.core.driver.entity.Driver;
import com.ecar.core.driver.entity.ModelSet;
import com.ecar.core.order.entity.Order;

import net.sf.json.JSONObject;

@Service
@Transactional
public class DriverServiceImpl implements DriverService{
	
	static Logger log = LoggerFactory.getLogger(AbstractResource.class);

	@Autowired
	DriverMapper driverMapper;
	
	@Autowired
	NotifyService notifyService;
	
	@Autowired
	ModelSetService modelSetService;
	
	@Autowired
	ModelSetMapper modelSetMapper;
	
	@Autowired
	OrderService orderService;
	
	@Autowired
	TempService tempService;
	
	@Override
	public Driver selectByPhone(String phone) {
		// TODO Auto-generated method stub
		return driverMapper.selectByPhone(phone);
	}
	
	@Override
	public DataBean logout(String driverId) {
		ModelSet modelSet=new ModelSet();
		modelSet.setDriverId(driverId);
		modelSet.setStatus(0);
		modelSetMapper.updateByDriverId(modelSet);
		
		return new DataBean(200,new JSONObject(),"退出登陆");
	}
	
	@Override
	public DataBean forgetPassword(JSONObject fields) {
		
		String phone = fields.getString("phone");
		String password=fields.getString("password");
		Pattern pattern = Pattern.compile("^[A-Za-z0-9!@\\$\\^\\*\\(\\)_`~\\-=,\\.;:<>\\?\\|]{8,22}$");
		Matcher matcher = pattern.matcher(password);
		if (!matcher.matches()) return new DataBean(403,new JSONObject(), "密码为8至22位字母数字和非特殊字符");
		
		if(fields.has("driverId")){
			String driverId = fields.getString("driverId");
			Driver driver=driverMapper.selectByPrimaryKey(driverId);
			if(driver==null){
				return new DataBean(404,new JSONObject(),"指定的用户不存在");
			}
			if(!driver.getPhone().equals(phone)){
				return new DataBean(403,new JSONObject(),"您无权修改其他人的密码");
			}
			
		}
		if(fields.has("captcha")){
			String captcha = fields.getString("captcha");
			if (StringUtil.isEmpty(captcha) || StringUtil.isEmpty(phone))
				return new DataBean(400,new JSONObject(), "参数错误，手机号和验证码不能为空。");
			String key= Redis.K.CAPTCHA.to(phone);
			String code = Redis.c.get(key);
			if (StringUtil.isEmpty(code)) return new DataBean(403, new JSONObject(),"验证码已过期！");
			else if (!captcha.equals(code)) return new DataBean(403, new JSONObject(),"手机号与验证码不匹配！");
			Redis.c.del(key);
		}else{
			return new DataBean(403,new JSONObject(),"参数错误");
		}
		Driver driver=driverMapper.selectByPhone(phone);
		if(driver==null){
			return new DataBean(404,new JSONObject(),"指定的用户不存在");
		}
		driver.setPassword(PasswordUtil.desencode(password));
		driverMapper.updateByPrimaryKey(driver);
		//修改密码就退出登陆
		if(fields.has("driverId")){
			this.logout(driver.getId());
		}
		return new DataBean(200,new JSONObject(),"密码修改成功");
	}

	@Override
	public DataBean login(JSONObject fields) {
		String phone = fields.getString("phone");
		String password = fields.getString("password");
		if (StringUtil.isEmpty(phone) || StringUtil.isEmpty(password))
			return new DataBean(400, new JSONObject(),"登录信息不能为空！");

		Driver driver = driverMapper.selectByPhone(phone);
		if (driver == null)
			return new DataBean(404, new JSONObject(),"登录失败，用户未找到。");
		
		String key = Redis.K.DRIVER_LOGIN.to(DateUtil.getCurDateYYYYMMDD(),phone);
		int count;
		if(Redis.c.exists(key)){
			count = Integer.valueOf(Redis.c.get(key));
		}else{
			count=0;
		}
		
		if(count>=5){
			return new DataBean(403,new JSONObject(),"登陆失败超过次数，请联系客服");
		}
		
		if (!password.equals(PasswordUtil.desdecode(driver.getPassword()))){
			log.info("错误登陆{}次数{}",phone,count+1);
			Redis.c.del(key);
			Redis.c.setex(Redis.K.DRIVER_LOGIN.to(DateUtil.getCurDateYYYYMMDD(),phone), Redis.DAY, (count+1)+"");
			return new DataBean(403,new JSONObject(), "登录失败，密码错误。");
		}
		Redis.c.del(key);
		//更新最新登陆时间
		//user.setLastLoginTime(new Date());
		//userMapper.updateByPrimaryKeySelective(user);
		// 登录日志
		//LogLogin logLogin = new LogLogin(user, ip, device, deviceInfo);
		//logLoginDao.save(logLogin);

		DriverDto result = new DriverDto();
		BeanUtils.copyProperties(driver, result);
		result.setPassword("");
		String id=driver.getId();
		ModelSet modelSet=modelSetService.selectByDriverId(id);
		if(modelSet==null){
			modelSet=new ModelSet();
		}
		
		result.setModelSet(modelSet);
		
		Redis.c.set(Redis.K.USER.to(id).getBytes(), BeanSerializer.serialize(result),
					Redis.NX.getBytes(), Redis.EX.getBytes(), Redis.M15);
		return new DataBean(200, result,"登陆成功");
	}
	
	//删除司机错误密码登陆次数
	@Override
	public Long deletLoginCount(String phone){
		String key = Redis.K.DRIVER_LOGIN.to(DateUtil.getCurDateYYYYMMDD(),phone);
		return Redis.c.del(key);
	}

	//司机注册
	@Override
	public DataBean regist(JSONObject fields) {
		String phone = fields.getString("phone");
		String password = fields.getString("password");
		String captcha = fields.getString("captcha");
		if (StringUtil.isEmpty(phone) || StringUtil.isEmpty(password) || StringUtil.isEmpty(captcha))
			return new DataBean(400, new JSONObject(),"注册信息不能为空！");

		//手机号验证
		Pattern patternP = Pattern.compile("^((13[0-9])|(14[5|7])|(15([0-9]))|(17([0-9]))|(18[0-9]))\\d{8}$");
		Matcher matcherP = patternP.matcher(phone);
		if (!matcherP.matches()) return new DataBean(403, new JSONObject(),"手机号有误");
		
		//验证码验证
		String key = Redis.K.CAPTCHA.to(phone);
		String code = Redis.c.get(key);
		if (StringUtil.isEmpty(code)) return new DataBean(403,new JSONObject(), "验证码已过期！");
		else if (!captcha.equals(code)) return new DataBean(403, new JSONObject(),"验证码错误！");

		//密码格式验证
		Pattern pattern = Pattern.compile("^[A-Za-z0-9!@\\$\\^\\*\\(\\)_`~\\-=,\\.;:<>\\?\\|]{8,22}$");
		Matcher matcher = pattern.matcher(password);
		if (!matcher.matches()) return new DataBean(403, new JSONObject(),"密码为8至22位字母数字和非特殊字符");
		
		//手机号验重
		Driver driver = driverMapper.selectByPhone(phone);
		if (driver != null)
		{
			return new DataBean(403,new JSONObject(), "手机号已注册!");
		}
		
		//验证通过后
		driver=new Driver();
		//前段没有给用户姓名，所以。。。
		driver.setId(UuidUtils.getUUID());
		driver.setName(phone);
		driver.setPhone(phone);
		driver.setRates(5.00D);
		//加密密码
		driver.setPassword(PasswordUtil.desencode(password));
		//创建时间
		driver.setCreateTime(new Date());
		int pk = driverMapper.insert(driver);
		if(pk<=0){
			return new DataBean(500,new JSONObject(),"注册失败");
		}
		
		String content = Props.getValue("sms.msg.regist");
		content = MessageFormat.format(content, driver.getName());
		// 20170407 同步发送短信
		if (!notifyService.sendSMS(phone, content)) {
			List<String> sms = new ArrayList<>();
			sms.add(driver.getPhone());
			sms.add(content);
			AsyncTheadPool.smsQueue.add(sms);
		}
		Redis.c.del(key);
		DataBean result=this.login(fields);
		result.setMessage("注册成功");
		return result;
	}

	@Override
	public int deleteByPrimaryKey(String id) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public int insert(Driver record) {
		// TODO Auto-generated method stub
		return driverMapper.insert(record);
	}

	@Override
	public int insertSelective(Driver record) {
		// TODO Auto-generated method stub
		return driverMapper.insertSelective(record);
	}

	@Override
	public Driver selectByPrimaryKey(String id) {
		// TODO Auto-generated method stub
		return driverMapper.selectByPrimaryKey(id);
	}

	/**
	 * @author fire
	 */
	@Override
	public DataBean updateByPrimaryKeySelective(Driver record) {
		if(driverMapper.selectByPrimaryKey(record.getId())==null){
			return new DataBean(403,new JSONObject(),"查无此人");
		};
		// TODO Auto-generated method stub
		int i=driverMapper.updateByPrimaryKeySelective(record);
		if(i<=0){
			return new DataBean(403, new JSONObject(),"司机个人资料提交失败");
			
		}
		return new DataBean(200, new JSONObject(),"司机个人资料提交成功");
	}

	@Override
	public int updateByPrimaryKey(Driver record) {
		// TODO Auto-generated method stub
		return driverMapper.updateByPrimaryKey(record);
	}

	//司机开始接单
	@Override
	public DataBean startGetOrder(String driverId) {
		Driver driver = driverMapper.selectByPrimaryKey(driverId);
		if (driver==null) {
			return new DataBean(400,new JSONObject(),"司机id错误!");
		}
		
		ModelSet modelSet = modelSetMapper.selectByDriverId(driverId);
		if (null==modelSet) {
			return new DataBean(402,new JSONObject(),"请先设置接单模式!");
		}
		
		//fire
		int a=orderService.countUnendOrderByDriverId(driverId);
		if(a!=0){
			return new DataBean(200,new JSONObject(),"司机还有未完成的订单!");
		}
		
		int i = modelSetMapper.startGetOrder(driverId);
		if (i==1) {
//			String licenseId = driver.getLicenseId();
//			if (null!=licenseId) {
//				tempService.postOperateLogin(driver );
//			}
			return new DataBean(200,new JSONObject(),"司机开始接单成功!");
		}else{
			return new DataBean(401,new JSONObject(),"司机开始接单失败!");
		}
	}

	//司机停止接单
	@Override
	public DataBean stopGetOrder(String driverId) {
		Driver driver = driverMapper.selectByPrimaryKey(driverId);
		if (driver==null) {
			return new DataBean(400,new JSONObject(),"司机id错误!");
		}
		
		int i = modelSetMapper.stopGetOrder(driverId);
		if (i==1) {
//			String licenseId = driver.getLicenseId();
//			if (null!=licenseId) {
//				tempService.postOperateLogOut(driver);
//			}
			return new DataBean(200,new JSONObject(),"司机停止接单成功!");
		}else{
			return new DataBean(401,new JSONObject(),"司机停止接单失败!");
		}
	}
}
